﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web.Configuration;
using Microsoft.Web.Administration;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Microsoft.Gateway.Utils
{
    public class AzureUtils
    {
        public static bool IsRunningInAzureWebRole()
        {
            bool retval = false;
            try
            {
                retval = RoleEnvironment.IsAvailable;
            }
            catch
            {
            }
            return retval;
        }

        public static void AddAzureDiagnosticsListener()
        {
            try
            {
                if (IsRunningInAzureWebRole())
                {
                    Trace.Listeners.Add(new DiagnosticMonitorTraceListener());
                }
            }
            catch (Exception e)
            {
                Trace.TraceWarning("Failed to load diagnostic listener: " + e.Message);
            }
        }

        public static string GetDefaultIISSiteName()
        {
            if (IsRunningInAzureWebRole())
            {
                return RoleEnvironment.CurrentRoleInstance.Id + "_Web";
            }
            return "Default Web Site";
        }

        public static bool TryGetConfigPath(out string configPath)
        {
            configPath = "";
            try
            {
                var gatewaySite = new ServerManager().Sites[AzureUtils.GetDefaultIISSiteName()];
                if (gatewaySite == null)
                {
                    return false;
                }

                configPath = Environment.ExpandEnvironmentVariables(Path.Combine(gatewaySite.Applications[0].VirtualDirectories[0].PhysicalPath, "web.config"));

                return true;
            }
            catch
            {
                return false;
            }

        }

        public static T GetConfigSetting<T>(string settingName, T defaultValue)
        {
            string configValue = CloudConfigurationManager.GetSetting(settingName);
            if (!String.IsNullOrWhiteSpace(configValue))
            {
                try
                {
                    if (typeof(T).IsEnum)
                    {
                        return (T)Enum.Parse(typeof(T), configValue);
                    }
                    return (T)Convert.ChangeType(configValue, typeof(T));
                }
                catch
                {
                }
            }
            return defaultValue;
        }

        public static void SetConfigSetting<T>(string settingName, T value)
        {
            var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");
            if (config.AppSettings.Settings.AllKeys.Contains(settingName, StringComparer.OrdinalIgnoreCase))
            {
                config.AppSettings.Settings.Remove(settingName);
            }
            config.AppSettings.Settings.Add(settingName, value.ToString());
            config.Save(ConfigurationSaveMode.Modified);
        }

        public static string GetLocalResourceLocation(string resourceName)
        {
            if (IsRunningInAzureWebRole())
            {
                try
                {
                    var resource = RoleEnvironment.GetLocalResource(resourceName);
                    return resource.RootPath;
                }
                catch (RoleEnvironmentException)
                {
                }
            }
            return Environment.ExpandEnvironmentVariables("%temp%");
        }
    }
}
